﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace DDASProject.ExtentLib
{

    public partial class IPControl : UserControl
    {
        private int _port;  //端口
        private const int FieldCount = 4;
        private bool _focused;
        private FieldControl[] _fieldControls = new FieldControl[FieldCount];
        public event EventHandler<FieldChangedEventArgs> FieldChangedEvent;

        public int Port
        {
            get { return _port; }
            set { _port = value; }
        }

        public override string Text
        {
            get
            {
                StringBuilder sb = new StringBuilder(); ;

                for (int index = 0; index < FieldCount; ++index)
                {
                    sb.Append(_fieldControls[index].Text);
                    sb.Append('.');
                   
                }

                return sb.ToString().TrimEnd('.');
            }
            set
            {
                Parse(value);
            }
        }

        public IPControl()
        {
            InitializeComponent();
            InitField();
            _port = 6101;
        }
        #region 公开接口
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Using Bytes seems more informative than SetAddressValues.")]
        public void SetAddressBytes(byte[] bytes)
        {
            Clear();

            if (bytes == null)
            {
                return;
            }

            int length = Math.Min(FieldCount, bytes.Length);

            for (int i = 0; i < length; ++i)
            {
                _fieldControls[i].Text = bytes[i].ToString();
            }
        }

        public void SetFieldFocus(int fieldIndex)
        {
            if ((fieldIndex >= 0) && (fieldIndex < FieldCount))
            {
                _fieldControls[fieldIndex].TakeFocus(Direction.Forward, Selection.All);
            }
        }

        public void SetFieldRange(int fieldIndex, byte rangeLower, byte rangeUpper)
        {
            if ((fieldIndex >= 0) && (fieldIndex < FieldCount))
            {
                _fieldControls[fieldIndex].RangeLower = rangeLower;
                _fieldControls[fieldIndex].RangeUpper = rangeUpper;
            }
        }
        public byte[] GetAddressBytes()
        {
            byte[] bytes = new byte[FieldCount];

            for (int index = 0; index < FieldCount; ++index)
            {
                bytes[index] = _fieldControls[index].Value;
            }

            return bytes;
        }

        public IPAddress GetIPAddress()
        {
            byte[] bytes = new byte[FieldCount];

            for (int index = 0; index < FieldCount; ++index)
            {
                bytes[index] = _fieldControls[index].Value;
            }

            return new IPAddress(bytes);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            for (int index = 0; index < FieldCount; ++index)
            {
                sb.Append(_fieldControls[index].ToString());
                sb.Append('.');
            }

            return sb.ToString().TrimEnd('.');
        }
        public void Clear()
        {
            foreach (FieldControl fc in _fieldControls)
            {
                fc.Clear();
            }
        }
        #endregion
        #region 内部函数



        //端口效验
        private void tbPort_Validating(object sender, CancelEventArgs e)
        {
            string port = tbPort.Text;
            if ("" == port)
            {
                e.Cancel = true;
            }
            try
            {
                int n = Convert.ToInt32(port);
                if (n < 1 || n > 65535)
                {
                    MessageBox.Show("您输入的值不能大于65535或小于1");
                    e.Cancel = true;
                    return;
                }
            }
            catch
            {
                MessageBox.Show("你输入的值非数字");
                e.Cancel = true;
            }
        }
        private void Parse(String text)
        {
            Clear();

            if (null == text)
            {
                return;
            }
            string ipFilter = @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))";
            bool isMatch = System.Text.RegularExpressions.Regex.IsMatch (text,ipFilter);
            if (isMatch)
            {
                string[] ipsub = text.Split('.');
                for (int i = 0; i < FieldCount;i++ )
                {
                    _fieldControls[i].Text = ipsub[i];
                }
            }
        }

        private void tbPort_Validated(object sender, EventArgs e)
        {
            _port = Convert.ToInt32(tbPort.Text);
        }

        private void InitField()
        {
            _fieldControls[0] = field1;
            _fieldControls[1] = field2;
            _fieldControls[2] = field3;
            _fieldControls[3] = field4;
            for (int index = 0; index < FieldCount; index++)
            {
                _fieldControls[index].CedeFocusEvent += new EventHandler<CedeFocusEventArgs>(OnCedeFocus);
                _fieldControls[index].GotFocus += new EventHandler(OnFieldGotFocus);
                _fieldControls[index].KeyDown += new KeyEventHandler(OnFieldKeyDown);
                _fieldControls[index].KeyPress += new KeyPressEventHandler(OnFieldKeyPressed);
                _fieldControls[index].KeyUp += new KeyEventHandler(OnFieldKeyUp);
                _fieldControls[index].LostFocus += new EventHandler(OnFieldLostFocus);
                _fieldControls[index].TextChangedEvent += new EventHandler<TextChangedEventArgs>(OnFieldTextChanged);
            }
        }
        private void OnCedeFocus(Object sender, CedeFocusEventArgs e)
        {
            switch (e.Action)
            {
                case Action.Home:

                    _fieldControls[0].TakeFocus(Action.Home);
                    return;

                case Action.End:

                    _fieldControls[FieldCount - 1].TakeFocus(Action.End);
                    return;

                case Action.Trim:

                    if (e.FieldIndex == 0)
                    {
                        return;
                    }

                    _fieldControls[e.FieldIndex - 1].TakeFocus(Action.Trim);
                    return;
            }

            if ((e.Direction == Direction.Reverse && e.FieldIndex == 0) ||
                 (e.Direction == Direction.Forward && e.FieldIndex == (FieldCount - 1)))
            {
                return;
            }

            int fieldIndex = e.FieldIndex;

            if (e.Direction == Direction.Forward)
            {
                ++fieldIndex;
            }
            else
            {
                --fieldIndex;
            }

            _fieldControls[fieldIndex].TakeFocus(e.Direction, e.Selection);
        }


        private void OnFieldGotFocus(Object sender, EventArgs e)
        {
            if (!_focused)
            {
                _focused = true;
                base.OnGotFocus(EventArgs.Empty);
            }
        }

        private void OnFieldKeyDown(Object sender, KeyEventArgs e)
        {
            OnKeyDown(e);
        }

        private void OnFieldKeyPressed(Object sender, KeyPressEventArgs e)
        {
            OnKeyPress(e);
        }


        private void OnFieldKeyUp(Object sender, KeyEventArgs e)
        {
            OnKeyUp(e);
        }

        private void OnFieldLostFocus(Object sender, EventArgs e)
        {
            if (!Focused)
            {
                _focused = false;
                base.OnLostFocus(EventArgs.Empty);
            }
        }

        private void OnFieldTextChanged(Object sender, TextChangedEventArgs e)
        {
            if (null != FieldChangedEvent)
            {
                FieldChangedEventArgs args = new FieldChangedEventArgs();
                args.FieldIndex = e.FieldIndex;
                args.Text = e.Text;
                FieldChangedEvent(this, args);
            }

            OnTextChanged(EventArgs.Empty);
        }
        #endregion
    }
    public class FieldChangedEventArgs : EventArgs
    {
        private int _fieldIndex;
        private String _text;

        public int FieldIndex
        {
            get { return _fieldIndex; }
            set { _fieldIndex = value; }
        }

        public String Text
        {
            get { return _text; }
            set { _text = value; }
        }
    }
}
